<template>
  <div class="chat-container">
    <div class="chat-header">
      <h1>AI 聊天界面</h1>
    </div>
    <div class="chat-messages" ref="chatMessagesRef">
      <div v-for="(message, index) in chatMessages" :key="index" :class="message.role === 'user' ? 'user-message' : 'ai-message'">
        <p>{{ message.content }}</p>
      </div>
      <div v-if="isLoading" class="loading-message">
        <p>正在思考，请稍候...</p>
      </div>
    </div>
    <div class="chat-input">
      <input
        v-model="userInput"
        type="text"
        placeholder="请输入你的问题..."
        @keyup.enter="sendMessage"
      />
      <button @click="sendMessage">发送</button>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      userInput: '',
      chatMessages: [],
      isLoading: false,
    };
  },
  methods: {
    async sendMessage() {
      if (this.userInput.trim() === '') return;

      // 添加用户消息到聊天记录
      const userMessage = { role: 'user', content: this.userInput };
      this.chatMessages.push(userMessage);
      this.userInput = ''; // 清空输入框
      this.isLoading = true; // 显示加载提示
      this.scrollToBottom(); // 滚动到底部

      try {
        // 发送请求到后端接口
        const response = await axios.get('http://localhost:8888/ask', {
          params: {
            question: userMessage.content,
          },
        });

        // 处理响应并添加 AI 消息到聊天记录
        const aiMessage = {
          role: 'assistant',
          content: response.data.choices[0].message.content,
        };
        this.chatMessages.push(aiMessage);
      } catch (error) {
        console.error('请求出错:', error);
        const errorMessage = {
          role: 'assistant',
          content: '请求出错，请稍后重试。',
        };
        this.chatMessages.push(errorMessage);
      } finally {
        this.isLoading = false; // 隐藏加载提示
        this.scrollToBottom(); // 滚动到底部
      }
    },
    scrollToBottom() {
      this.$nextTick(() => {
        const chatMessagesDiv = this.$refs.chatMessagesRef;
        chatMessagesDiv.scrollTop = chatMessagesDiv.scrollHeight;
      });
    },
  },
};
</script>

<style scoped>
    @import "./chat.css";
</style>